package com.dliyun.oap.framework.impl;

import com.dliyun.oap.framework.exception.OapException;
import com.dliyun.oap.framework.security.AppSecretManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.util.Properties;

/**
 * <pre>
 * 基于文件管理的应用密钥
 * </pre>
 *
 * @author stjdydayou
 * @version 1.0
 */
@Slf4j
public class FileBaseAppSecretManager implements AppSecretManager {

    private static final String OAP_APP_SECRET_PROPERTIES = "oap.appSecret.properties";

    private static Properties properties;

    public static String getSecret(String appKey) {
        if (properties == null) {
            try {
                DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
                Resource resource = resourceLoader.getResource(OAP_APP_SECRET_PROPERTIES);
                properties = PropertiesLoaderUtils.loadProperties(resource);
            } catch (IOException e) {
                throw new OapException("在类路径下找不到oap.appSecret.properties的应用密钥的属性文件", e);
            }
        }
        String secret = properties.getProperty(appKey);

        if (StringUtils.isBlank(secret)) {
            log.error("不存在应用键为{}的密钥,请检查应用密钥的配置文件。", appKey);
            return "";
        }
        return secret;
    }

    @Override
    public boolean isValidAppKey(String appKey) {
        return StringUtils.isNotBlank(appKey) && FileBaseAppSecretManager.getSecret(appKey) != null;
    }
}
